package com.sangeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sangeng.constant.LoginConstants;
import com.sangeng.constant.SystemConstants;
import com.sangeng.domain.entity.LoginUser;
import com.sangeng.domain.entity.User;
import com.sangeng.mapper.MenuMapper;
import com.sangeng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,s);
        User user = userService.getBaseMapper().selectOne(queryWrapper);
        // 判断是否存在用户，如果没查到就抛出异常
        if(Objects.isNull(user)) throw new RuntimeException(LoginConstants.LOGIN_USER_NOT_EXIST_MESSAGE);

        // 判断是否是后台用户
        if(user.getType().equals(SystemConstants.Admin_USER)){
            // 后台用户增加权限信息
            List<String> permissions = menuMapper.selectPermsByUserId(user.getId());
            return new LoginUser(user,permissions);
        }

        return new LoginUser(user);
    }
}
